package com.example.foo.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.order.dao.OrderDao;
import com.example.foo.order.model.Order;
import com.example.foo.order.query.OrderQuery;
import com.example.foo.product.model.Item;
import com.example.foo.weixin.utils.Utility;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@org.springframework.stereotype.Service
public class OrderService {

    private final OrderDao orderDao;

    public OrderService(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    // ========== Order ==========

    public PageResult<Order> findOrders(OrderQuery orderQuery, Pageable pageable) {
        return orderDao.findOrders(orderQuery, pageable);
    }

    public List<Order> findOrdersByIds(List<Long> ids) {
        return orderDao.selectBatchIds(ids);
    }

    public Order findOrderById(Long id) {
        return orderDao.selectById(id);
    }

    public List<Order> findOrderList(OrderQuery orderQuery) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>(orderQuery);
        if (StringUtils.isNotEmpty(orderQuery.getAppIdList())) {
            queryWrapper.in("app_id", Arrays.asList(orderQuery.getAppIdList().split(",")));
        }
        queryWrapper.orderByDesc("id");
        return orderDao.selectList(queryWrapper);
    }

    public List<Order> findZjShareOrders(String date) {
        return orderDao.findZjShareOrders(date);
    }
    public List<Order> findOrdersByStatus(Integer status,String beforeTenDay) {
        List<Order> orders = orderDao.selectList(new QueryWrapper<Order>().eq("status", status).apply("date_format(delivery_time,'%Y-%m-%d') = {0}", beforeTenDay));
        return orders;
    }

    public int findPayGoodsNumByUid(Long uid,String goodsType) {
        Long count = orderDao.selectCount(new QueryWrapper<Order>().eq("uid", uid).eq("goods_type",goodsType).eq("pay_status",1));
        return count.intValue();
    }

    //查询用户已领礼品数量
    public int findGiftNumByUid(Long uid,String giftType) {
        Long count = orderDao.selectCount(new QueryWrapper<Order>().eq("uid", uid).eq("goods_type",giftType));
        return count.intValue();
    }

    //判断用户购买的的订单是否领取过礼包
    public int findGiftNumByPid(Long uid,String giftType,Long orderId) {
        Long count = orderDao.selectCount(new QueryWrapper<Order>().eq("uid", uid).eq("goods_type",giftType).eq("pid",orderId));
        return count.intValue();
    }

    public List<Order> findPayGoodsByUid(Long uid,String goodsType) {
        List<Order> orders = orderDao.selectList(new QueryWrapper<Order>().eq("uid", uid).eq("goods_type",goodsType).eq("pay_status",1));
        return orders;
    }

    public Order findOrderByOutTradeNo(String outTradeNo) {
        Order order = orderDao.selectOne(new QueryWrapper<Order>().eq("out_trade_no", outTradeNo));
        return order;
    }

    public List<Order> findOrdersByUid(Long uid) {
        List<Order> orders = orderDao.selectList(new QueryWrapper<Order>().eq("uid", uid));
        return orders;
    }

    public Order createOrder(String outTradeNo, String cardSn, String realName, Long uid, Item item, BigDecimal deductionAmount, String userPhone, String province,String city,String district,String addressDetail, String goodsDetail, String goodsType, BigDecimal totalPrice, Integer handlingMethod, String payType,Long lxChannelId,String appId) {
        Order order = new Order();
        order.setOutTradeNo(outTradeNo);
        order.setCardSn(cardSn);
        order.setRealName(realName);
        order.setUid(uid);
        order.setItemId(item.getId());
        order.setUserPhone(userPhone);
        order.setProvince(province);
        order.setCity(city);
        order.setDistrict(district);
        order.setAddressDetail(addressDetail);
        order.setGoodsDetail(goodsDetail);
        order.setPicUrl(item.getPicUrl());
        order.setPicUrlJson(item.getPicUrlJson());
        order.setBody(item.getBody());
        order.setGoodsType(goodsType);
        order.setTotalPrice(totalPrice);
        order.setDeductionAmount(deductionAmount);
        order.setHandlingMethod(handlingMethod);
        order.setPayType(payType);
        order.setLxChannelId(lxChannelId);
        order.setAppId(appId);
        order.setCreatedAt(LocalDateTime.now());
        orderDao.insert(order);
        return order;
    }

    public Order createGiftOrder(Long pid,String cardSn,String realName, Long uid, Item item, String giftType, String userPhone, String province,String city,String district,String addressDetail, String goodsDetail, BigDecimal totalPrice,String appId) {
        Order order = new Order();
        order.setPid(pid);
        order.setOutTradeNo(Utility.generateUUID());
        order.setCardSn(cardSn);
        order.setRealName(realName);
        order.setUid(uid);
        order.setItemId(item.getId());
        order.setUserPhone(userPhone);
        order.setProvince(province);
        order.setCity(city);
        order.setDistrict(district);
        order.setAddressDetail(addressDetail);
        order.setGoodsDetail(goodsDetail);
        order.setPicUrl(item.getPicUrl());
        order.setPicUrlJson(item.getPicUrlJson());
        order.setBody(item.getBody());
        order.setGoodsType(giftType);
        order.setTotalPrice(totalPrice);
        order.setHandlingMethod(Order.HandlingMethod.give.val);
        order.setPayStatus(Order.PayStatus.processed.val);
        order.setStatus(Order.Status.pending.val);
        order.setAppId(appId);
        order.setCreatedAt(LocalDateTime.now());
        orderDao.insert(order);
        return order;
    }

    public int updateOrder(Order order) {
        order.setUpdatedAt(LocalDateTime.now());
        int row = orderDao.updateById(order);
        return row;
    }

    @Transactional(rollbackFor = Exception.class)
    public int addBackUserInfoId(Long id,Long backUserInfoId){
        Order order = new Order();
        order.setId(id);
        order.setBackUserInfoId(backUserInfoId);
        order.setUpdatedAt(LocalDateTime.now());
        int row = orderDao.updateById(order);
        return row;
    }
}
